/*
 * @Author: xiaosihan
 * @Date: 2025-08-24 10:00:00
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-10-01 10:00:00
 */

// PC页面模板组件 - 严格遵循此模板的导入顺序和格式
import React, { useEffect, useState } from 'react';

// 页面样式必须要使用module.less后缀的文件
import clsx from 'clsx';
import styles from './dataViewer.module.less';

// 每个页面都需要引入对应的store
import dataViewerStore from './dataViewerStore';
import { toJS } from 'mobx';

// PC端使用observer来包裹组件，使mobx可以监听状态变化
import { observer } from 'mobx-react-lite';

// Ant Design组件导入
import { Button, Card, Empty, InputNumber, Input, Pagination, Select, Spin, Switch, Table, Tooltip, Typography, Modal } from 'antd';

const { Title, Text } = Typography;
const { Column } = Table;

// 组件props接口定义
interface Iprops {
    children?: React.ReactNode;
}

/**
 * DataViewer页面组件
 * 遵循项目统一的开发规范
 */
// 重要：组件函数不要使用React.FC类型注解
const DataViewer = observer((props: Iprops) => {
    // store中的基本类型状态值，使用解构方式获取
    const { designLoading, ossFileLoading, designData, ossFileData } = dataViewerStore;

    // store中的数组或对象类型状态值，使用toJS方法获取
    const designDataList = toJS(designData);
    const ossFileDataList = toJS(ossFileData);

    // 初始加载数据
    useEffect(() => {
        dataViewerStore.initializeData();
    }, []);

    // 控制弹窗显示的状态
    const [isEditModalVisible, setIsEditModalVisible] = useState<boolean>(false);
    const [currentEditRecord, setCurrentEditRecord] = useState<any>(null);

    // 用于处理和显示长文本的函数
    // 用于显示长文本的截断函数
    const processAndTruncateText = (text: string, maxLength: number = 100) => {
        if (!text) return '';
        // 去掉特定的字符串: " `http://www-3dkeshihua.oss-cn-shanghai.aliyuncs.com` "
        const processedText = text.replace("http://www-3dkeshihua.oss-cn-shanghai.aliyuncs.com", '');
        return processedText.length > maxLength ? processedText.substring(0, maxLength) + '...' : processedText;
    };

    // 打开编辑弹窗
    const showEditModal = (record: any) => {
        setCurrentEditRecord(record);
        dataViewerStore.startEditing(record.id, record.data, record.order);
        setIsEditModalVisible(true);
    };

    // 关闭编辑弹窗
    const handleEditModalCancel = () => {
        setIsEditModalVisible(false);
        dataViewerStore.cancelEdit();
    };

    // 提交编辑
    const handleEditModalOk = async () => {
        await dataViewerStore.submitEdit();
        setIsEditModalVisible(false);
    };

    return (
        <div className={styles.content}>
            <Title level={2}>数据查看器</Title>

            <div className={styles.tablesContainer}>
                {/* 左侧Design表 */}
                <Card className={styles.leftCard} title="Design数据" extra={
                    <div className={styles.cardExtra}>
                        <div className={styles.actionGroup}>
                            <Button
                                type="primary"
                                onClick={dataViewerStore.handleAddDesignData}
                                loading={dataViewerStore.addingData}
                                disabled={dataViewerStore.addingData || dataViewerStore.randomSettingData || dataViewerStore.clearingDesignData}
                            >
                                添加数据
                            </Button>
                            <Button
                                type="default"
                                onClick={dataViewerStore.handleRandomSetDesignData}
                                loading={dataViewerStore.randomSettingData}
                                disabled={dataViewerStore.addingData || dataViewerStore.randomSettingData || dataViewerStore.clearingDesignData}
                            >
                                随机设置数据
                            </Button>
                        </div>
                        <div className={styles.filters}>
                            <div className={styles.filterItem}>
                                <span>只显示重复data</span>
                                <Switch
                                    checked={dataViewerStore.onlyDuplicateData}
                                    onChange={dataViewerStore.setOnlyDuplicateData}
                                    disabled={dataViewerStore.designLoading}
                                />
                            </div>
                            <div className={styles.filterItem}>
                                <span>只显示非空data</span>
                                <Switch
                                    checked={dataViewerStore.requireNonEmptyData}
                                    onChange={dataViewerStore.setRequireNonEmptyData}
                                    disabled={dataViewerStore.designLoading}
                                />
                            </div>
                        </div>
                        <div className={clsx(styles.dangerGroup, styles.mlAuto)}>
                            <Button
                                danger
                                onClick={dataViewerStore.handleClearDesignData}
                                loading={dataViewerStore.clearingDesignData}
                                disabled={dataViewerStore.clearingDesignData || dataViewerStore.addingData || dataViewerStore.randomSettingData || dataViewerStore.deletingAllDesignData}
                            >
                                清空data字段
                            </Button>
                            <Button
                                danger
                                type="link"
                                onClick={dataViewerStore.handleDeleteAllDesignData}
                                loading={dataViewerStore.deletingAllDesignData}
                                disabled={dataViewerStore.deletingAllDesignData || dataViewerStore.addingData || dataViewerStore.randomSettingData || dataViewerStore.clearingDesignData}
                            >
                                删除全部数据
                            </Button>
                        </div>
                    </div>
                }>
                    {dataViewerStore.designData.length > 0 ? (
                        <Spin size="large" spinning={dataViewerStore.designLoading} >

                            <div className={styles.tableWrapper}>

                                <Table
                                    dataSource={dataViewerStore.designData}
                                    rowKey="id"
                                    pagination={false}
                                    scroll={{ y: 600 }}
                                    className={styles.table}
                                    size="small"
                                >
                                    <Column
                                        title="序号"
                                        key="serial-number"
                                        width={60}
                                        render={(text, record, index) => {
                                            // 计算序号：当前索引 + 1 + (当前页码 - 1) * 页大小
                                            return index + 1 + (dataViewerStore.designCurrentPage - 1) * dataViewerStore.pageSize;
                                        }}
                                    />
                                    <Column title="ID" dataIndex="id" key="id" width={80} />
                                    <Column
                                        title="Data"
                                        dataIndex="data"
                                        key="data"
                                        ellipsis
                                        render={(text) => {
                                            const processedText = processAndTruncateText(text);
                                            return (
                                                <Tooltip title={processedText}>
                                                    <Text>{processedText}</Text>
                                                </Tooltip>
                                            );
                                        }}
                                    />
                                    <Column
                                        title="当前顺序"
                                        dataIndex="order"
                                        key="current-order"
                                        width={100}
                                        render={(order) => {
                                            return order || 0;
                                        }}
                                    />
                                    <Column
                                        title="操作"
                                        key="action"
                                        width={160}
                                        render={(text, record) => (
                                            <Button
                                                type="primary"
                                                size="small"
                                                onClick={() => showEditModal(record)}
                                                disabled={dataViewerStore.updatingData || dataViewerStore.sortingData !== null}
                                            >
                                                编辑
                                            </Button>
                                        )}
                                    />
                                </Table>
                            </div>
                            <div className={styles.paginationContainer}>
                                <Pagination
                                    current={dataViewerStore.designCurrentPage}
                                    pageSize={dataViewerStore.pageSize}
                                    total={dataViewerStore.designTotal}
                                    onChange={(page, pageSize) => dataViewerStore.handleDesignPageChange(page, pageSize)}
                                    showSizeChanger
                                    showTotal={(total) => `共 ${total} 条`}
                                />
                            </div>
                        </Spin>
                    ) : (
                        <Empty description="暂无数据" className={styles.emptyContainer} />
                    )}
                </Card>

                {/* 右侧OSS文件表 */}
                <Card className={styles.rightCard} title="OSS文件数据" extra={
                    <div className={styles.cardExtra}>
                        <div className={styles.cardExtra}>
                            <Select
                                placeholder="使用状态"
                                className={styles.selectWidth}
                                onChange={(value) => dataViewerStore.setOssFileFilter({ used: value })}
                                allowClear
                            >
                                <Select.Option value="all">全部</Select.Option>
                                <Select.Option value="unknown">未知</Select.Option>
                                <Select.Option value="used">已使用</Select.Option>
                                <Select.Option value="nouse">未使用</Select.Option>
                            </Select>
                            <div className={styles.filterItem}>
                                <span>只显示重复url</span>
                                <Switch
                                    checked={dataViewerStore.onlyDuplicateUrl}
                                    onChange={dataViewerStore.setOnlyDuplicateUrl}
                                    disabled={dataViewerStore.ossFileLoading}
                                />
                            </div>
                        </div>
                        <div className={clsx(styles.actionGroup, styles.mlAuto)}>
                            <Button
                                type="primary"
                                onClick={dataViewerStore.handleCheckOssFileUsageStatus}
                                loading={dataViewerStore.checkingOssUsageStatus}
                                disabled={dataViewerStore.checkingOssUsageStatus || dataViewerStore.resettingOssStatus}
                            >
                                检查使用状态
                            </Button>
                            <Button
                                type="default"
                                onClick={dataViewerStore.handleResetOssFileUsedStatus}
                                loading={dataViewerStore.resettingOssStatus}
                                disabled={dataViewerStore.resettingOssStatus || dataViewerStore.checkingOssUsageStatus}
                            >
                                重置使用状态
                            </Button>
                        </div>
                    </div>
                }>
                    {dataViewerStore.ossFileData.length > 0 ? (
                        <Spin size="large" spinning={dataViewerStore.ossFileLoading} >
                            <div className={styles.tableWrapper}>
                                <Table
                                    dataSource={dataViewerStore.ossFileData}
                                    rowKey="file_id"
                                    pagination={false}
                                    scroll={{ y: 600 }}
                                    className={styles.table}
                                    size="small"
                                >
                                    <Column
                                        title="序号"
                                        key="serial-number"
                                        width={60}
                                        render={(text, record, index) => {
                                            // 计算序号：当前索引 + 1 + (当前页码 - 1) * 页大小
                                            return index + 1 + (dataViewerStore.ossFileCurrentPage - 1) * dataViewerStore.pageSize;
                                        }}
                                    />
                                    <Column title="文件ID" dataIndex="file_id" key="file_id" width={150} />
                                    <Column
                                        title="URL"
                                        dataIndex="url"
                                        key="url"
                                        ellipsis
                                        render={(text) => (
                                            <Tooltip title={text}>
                                                <Text>{processAndTruncateText(text, 50)}</Text>
                                            </Tooltip>
                                        )}
                                    />
                                    <Column title="后缀" dataIndex="suffix" key="suffix" width={80} />
                                    <Column title="是否优化" dataIndex="optimized" key="optimized" width={120} />
                                    <Column title="使用状态" dataIndex="used" key="used" width={120} />
                                </Table>
                            </div>
                            <div className={styles.paginationContainer}>
                                <Pagination
                                    current={dataViewerStore.ossFileCurrentPage}
                                    pageSize={dataViewerStore.pageSize}
                                    total={dataViewerStore.ossFileTotal}
                                    onChange={(page, pageSize) => dataViewerStore.handleOssFilePageChange(page, pageSize)}
                                    showSizeChanger
                                    showTotal={(total) => `共 ${total} 条`}
                                />
                            </div>
                        </Spin>
                    ) : (
                        <Empty description="暂无数据" className={styles.emptyContainer} />
                    )}
                </Card>
            </div>

            {/* 查找匹配数据按钮 - 放置在两个表格的下方 */}
            <div className={styles.matchSection}>
                <Button
                    type="primary"
                    onClick={dataViewerStore.handleMatchAndUpdateData}
                    loading={dataViewerStore.designLoading || dataViewerStore.ossFileLoading}
                >
                    查找匹配数据并更新
                </Button>
                <div className={styles.matchDesc}>
                    说明：此功能将从design表格中查找design.data等于oss_file.url的数据
                    并将找到的数据的design.data设置为空，oss_file.used设置为nouse
                </div>
            </div>

            {/* 编辑弹窗 */}
            <Modal
                title="编辑数据"
                open={isEditModalVisible}
                onOk={handleEditModalOk}
                onCancel={handleEditModalCancel}
                okText="确认"
                cancelText="取消"
                width={600}
                centered
                confirmLoading={dataViewerStore.updatingData}
            >
                {currentEditRecord && (
                    <div>
                        <Table
                            dataSource={[currentEditRecord]}
                            pagination={false}
                            size="small"
                            rowKey="id"
                            scroll={{ x: 'max-content' }}
                        >
                            <Column title="ID" dataIndex="id" key="id" width={80} />
                            <Column
                                title="Data"
                                key="data"
                                render={() => (
                                    <Input.TextArea
                                        rows={2}
                                        value={dataViewerStore.editingData}
                                        onChange={dataViewerStore.handleEditDataChange}
                                        placeholder="请输入数据"
                                        className={styles.modalInputWide}
                                    />
                                )}
                            />
                            <Column
                                title="顺序"
                                key="order"
                                render={() => (
                                    <InputNumber
                                        min={0}
                                        value={dataViewerStore.editingOrder}
                                        onChange={dataViewerStore.handleEditOrderChange}
                                        className={styles.modalNumberWidth}
                                    />
                                )}
                            />
                        </Table>
                    </div>
                )}
            </Modal>
        </div>
    );
});

export default DataViewer;
